package com.formiaomiao.demain.activity;

import android.annotation.SuppressLint;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.drawable.ColorDrawable;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.v4.content.FileProvider;
import android.support.v7.app.AppCompatActivity;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.formiaomiao.demain.BuildConfig;
import com.formiaomiao.demain.R;
import com.formiaomiao.demain.base.BaseActivity;

import java.io.File;

/**
 * ch
 * 相册 基础类
 */
public abstract class PicActivity extends BaseActivity {

    public static final String COM_CAMERA_PHOTO_FILEPROVIDER = "com.formiaomiao.demain.fileprovider";
    private PopupWindow pop;
    private TextView tv_photograph;
    private TextView tv_album;
    private LinearLayout ll_cancle_layout;
    /**
     * 基础路径
     */

    private String basePath;
    /**
     * 裁剪存放路径
     */
    private String corpPath = "corp/";
    /**
     * 拍照
     */
    private static final int REQUEST_CODE_CAPTURE_CAMEIA = 0;
    /**
     * 从相册选择
     */
    private static final int REQUEST_CODE_PICK_IMAGE = 1;
    /**
     * 剪切
     */
    private static final int CROP_REQUEST_CODE = 4;
    /**
     * 返回路径
     */
    private Uri photoUri;
    /**
     * 是否裁剪
     */
    public boolean iscorp;
    private String crop;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    /**
     * 相册回调
     *
     * @param path
     */
    public abstract void formAlbum(String path);

    /**
     * 相机回调
     *
     * @param path
     */
    public abstract void formCamera(String path);

    /**
     * 裁剪回调
     *
     * @param path
     */
    public abstract void formCorp(String path);


    /**
     * 显示选择pop
     *
     * @param parent
     * @param basePath /mayatu/
     * @param iscorp   是否裁剪
     */
    public void showPicPopWindow(View parent, String basePath, boolean iscorp) {
        this.iscorp = iscorp;
        this.basePath = Environment.getExternalStorageDirectory() + basePath;
        View view = LayoutInflater.from(PicActivity.this).inflate(R.layout.popw_alert_select_phone, null);
        initView(view);
        // 设置SelectPicPopupWindow的View
        pop = new PopupWindow(PicActivity.this);
        pop.setContentView(view);
        // 设置SelectPicPopupWindow弹出窗体的宽
        pop.setWidth(ViewGroup.LayoutParams.MATCH_PARENT);
        // 设置SelectPicPopupWindow弹出窗体的高
        pop.setHeight(ViewGroup.LayoutParams.MATCH_PARENT);
        // 设置SelectPicPopupWindow弹出窗体可点击
        pop.setFocusable(true);
        // 实例化一个ColorDrawable颜色为半透明
        ColorDrawable dw = new ColorDrawable(0xb0000000);
        // 设置SelectPicPopupWindow弹出窗体的背景
        pop.setBackgroundDrawable(dw);
        // 获取当前打开的界面的 父View
        // mMenuView添加OnTouchListener监听判断获取触屏位置如果在选择框外面则销毁弹出框
        view.setOnTouchListener(new View.OnTouchListener() {

            @SuppressLint("ClickableViewAccessibility")
            public boolean onTouch(View v, MotionEvent event) {
                pop.dismiss();
                return true;
            }
        });
        pop.showAtLocation(parent, Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, 0);
    }

    private void initView(View view) {
        tv_photograph = (TextView) view.findViewById(R.id.tv_photograph);
        tv_album = (TextView) view.findViewById(R.id.tv_album);
        ll_cancle_layout = (LinearLayout) view.findViewById(R.id.ll_cancle_layout);
        tv_photograph.setOnClickListener(new MyOnClickListener());
        tv_album.setOnClickListener(new MyOnClickListener());
        ll_cancle_layout.setOnClickListener(new MyOnClickListener());
    }


    private class MyOnClickListener implements OnClickListener {

        @Override
        public void onClick(View v) {
            switch (v.getId()) {
                // 拍照
                case R.id.tv_photograph:

                    getImageFromCamera();

                    if (pop != null) {
                        pop.dismiss();
                    }
                    break;
                // 相册
                case R.id.tv_album:
                    getImageFromAlbum();// 从相册里获取
                    if (pop != null) {
                        pop.dismiss();
                    }
                    break;
                // 取消
                case R.id.ll_cancle_layout:
                    if (pop != null) {
                        pop.dismiss();
                    }
                    break;

                default:
                    break;
            }
        }
    }

    /**
     * 从相册里选取
     */
    protected void getImageFromAlbum() {

        Intent intent = new Intent(Intent.ACTION_PICK);
        intent.setType("image/*");
        startActivityForResult(intent, REQUEST_CODE_PICK_IMAGE);
    }

    /**
     * 获取安卓系统照相机拍照
     */
    protected void getImageFromCamera() {

        Intent getImageByCamera = new Intent("android.media.action.IMAGE_CAPTURE");

        String state = Environment.getExternalStorageState();
        if (state.equals(Environment.MEDIA_MOUNTED)) {// 检查是否有存储卡
            // 创建位置

            File fileDir = new File(basePath);
            if (!fileDir.exists()) {// 目录是否存在
                fileDir.mkdirs();// 删掉
            }

            File file = new File(basePath + System.currentTimeMillis() + ".jpg");
            if (Build.VERSION.SDK_INT < Build.VERSION_CODES.N) {

                photoUri = Uri.fromFile(file); // Create path for temp file
                // 相机存储的地址
                getImageByCamera.putExtra(MediaStore.EXTRA_OUTPUT, photoUri);
                startActivityForResult(getImageByCamera, REQUEST_CODE_CAPTURE_CAMEIA);// 拍照完送去裁剪
            } else {
                photoUri = FileProvider.getUriForFile(getApplicationContext(), BuildConfig.APPLICATION_ID+".provider",file);
                getImageByCamera.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
                getImageByCamera.putExtra(MediaStore.EXTRA_OUTPUT, photoUri);
                startActivityForResult(getImageByCamera, REQUEST_CODE_CAPTURE_CAMEIA);
            }

        }
    }

    /**
     * 转换 content:// uri
     *
     * @param imageFile
     * @return
     */
    public Uri getImageContentUri(File imageFile) {
        String filePath = imageFile.getAbsolutePath();
        Cursor cursor = getContentResolver().query(
                MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
                new String[] { MediaStore.Images.Media._ID },
                MediaStore.Images.Media.DATA + "=? ",
                new String[] { filePath }, null);

        if (cursor != null && cursor.moveToFirst()) {
            int id = cursor.getInt(cursor
                    .getColumnIndex(MediaStore.MediaColumns._ID));
            Uri baseUri = Uri.parse("content://media/external/images/media");
            return Uri.withAppendedPath(baseUri, "" + id);
        } else {
            if (imageFile.exists()) {
                ContentValues values = new ContentValues();
                values.put(MediaStore.Images.Media.DATA, filePath);
                return getContentResolver().insert(
                        MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
            } else {
                return null;
            }
        }
    }

    /**
     * 裁剪
     *
     * @param uri
     */
    private void startPhotoZoom(Uri uri) {
        try {
            // ========================================
            File fileDir = new File(basePath + corpPath);
            if (!fileDir.exists()) {// 目录是否存在
                fileDir.mkdirs();// 创建
            }

            crop = basePath + corpPath + System.currentTimeMillis() + ".jpg";

            Uri imageUri = null;
//            if (Build.VERSION.SDK_INT < Build.VERSION_CODES.N) {
            imageUri = Uri.parse("file://" + crop);
//            } else {
//                imageUri = FileProvider.getUriForFile(context, "com.camera.photos.fileprovider", new File(crop));
//            }

            final Intent intent = new Intent("com.android.camera.action.CROP");
            intent.setDataAndType(uri, "image/*");
            intent.putExtra("crop", "true");
            intent.putExtra("aspectX", 1);
            intent.putExtra("aspectY", 1);
            intent.putExtra("outputX", 200);
            intent.putExtra("outputY", 200);
            intent.putExtra("noFaceDetection", false); // 不启用人脸识别
            intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
            intent.putExtra("outputFormat", Bitmap.CompressFormat.JPEG.toString());
            intent.putExtra("noFaceDetection", false);
            intent.putExtra("return-data", false);
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            startActivityForResult(intent, CROP_REQUEST_CODE);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
            // 拍照回调
            case REQUEST_CODE_CAPTURE_CAMEIA:
                if (iscorp) {
                    startPhotoZoom(photoUri);
                } else {
                    formCamera(photoUri.getPath());
//                    getRealPathFromUri(photoUri);
                }

                break;
            // 从相册里选取
            case REQUEST_CODE_PICK_IMAGE:
                if (null != data) {
                    Uri uri = data.getData();
                    if (uri != null) {
                        if (iscorp) {
                            startPhotoZoom(uri);
                        } else {
                            formAlbum(uri.getPath());
//                            getRealPathFromUri(uri);
                        }
                    }
                }

                break;
            // 剪切
            case CROP_REQUEST_CODE:
                formCorp(crop);
                break;

        }
    }


}
